import React, { useState, useEffect, useRef } from 'react'
import './swiper.scss'

function Swiper() {
  // 当前幻灯片索引
  const [currentIndex, setCurrentIndex] = useState(0)
  // 自动播放状态
  const [autoPlay, setAutoPlay] = useState(true)
  // 触摸开始时的X坐标
  const touchStartX = useRef(0)
  // 定时器引用
  const intervalRef = useRef<NodeJS.Timeout>()
  const slides = [
    { id: 1, color: '#ff6b6b', content: 'Slide 1' },
    { id: 2, color: '#4ecdc4', content: 'Slide 2' },
    { id: 3, color: '#45b7d1', content: 'Slide 3' },
  ]

  // 自动播放逻辑
  useEffect(() => {
    if (autoPlay) {
      intervalRef.current = setInterval(() => {
        nextSlide()
      }, 5000)
    }
    return () => clearInterval(intervalRef.current)
  }, [autoPlay, currentIndex])

  // 幻灯片切换
  const nextSlide = () => {
    setCurrentIndex(prev => (prev === slides.length - 1 ? 0 : prev + 1))
  }

  const prevSlide = () => {
    setCurrentIndex(prev => (prev === 0 ? slides.length - 1 : prev - 1))
  }

  // 触摸事件处理
  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX
  }
 
  const handleTouchEnd = (e: React.TouchEvent) => {
    const touchEndX = e.changedTouches[0].clientX
    const diff = touchStartX.current - touchEndX
    
    if (Math.abs(diff) > 50) {
      diff > 0 ? nextSlide() : prevSlide()
    }
  }

  return (
    <div 
      className="swiper-container"
      onMouseEnter={() => setAutoPlay(false)}
      onMouseLeave={() => setAutoPlay(true)}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      {/* 幻灯片内容 */}
      <div 
        className="slides-wrapper"
        style={{ transform: `translateX(-${currentIndex * 100}%)` }}
      >
        {slides.map((slide, index) => (
          <div 
            key={slide.id}
            className="slide"
            style={{ 
              backgroundColor: slide.color,
              left: `${index * 100}%`
            }}
          >
            <h2>{slide.content}</h2>
          </div>
        ))}
      </div>

      {/* 导航箭头 */}
      <button className="nav-button prev" onClick={prevSlide}>
        &lt;
      </button>
      <button className="nav-button next" onClick={nextSlide}>
        &gt;
      </button>

      {/* 指示点 */}
      <div className="pagination">
        {slides.map((_, index) => (
          <span
            key={index}
            className={`dot ${index === currentIndex ? 'active' : ''}`}
            onClick={() => setCurrentIndex(index)}
          />
        ))}
      </div>
    </div>
  )
}

export default Swiper